import { Component, inject } from '@angular/core';
import { NonNullableFormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd/message';
import { AuthService } from '../../services/auth.service';
import { SignupRequest } from '../../models/auth.model';

@Component({
  selector: 'app-register',
  standalone: false,
  templateUrl: './register.component.html',
  styleUrl: './register.component.less',
})
export class RegisterComponent {
  private fb = inject(NonNullableFormBuilder);
  private authService = inject(AuthService);
  private router = inject(Router);
  private message = inject(NzMessageService);

  // 创建响应式表单
  registerForm = this.fb.group({
    name: ['', [Validators.required, Validators.minLength(2)]],
    email: ['', [Validators.required, Validators.email]],
    password: ['', [Validators.required, Validators.minLength(6)]],
    confirmPassword: ['', [Validators.required]],
    agree: [false, [Validators.requiredTrue]]
  }, {
    validators: this.passwordMatchValidator
  });

  // 加载状态
  loading = false;

  // 密码确认验证器
  passwordMatchValidator(form: any) {
    const password = form.get('password')?.value;
    const confirmPassword = form.get('confirmPassword')?.value;

    if (password !== confirmPassword) {
      form.get('confirmPassword')?.setErrors({ mismatch: true });
      return { mismatch: true };
    } else {
      const confirmPasswordControl = form.get('confirmPassword');
      if (confirmPasswordControl?.errors?.['mismatch']) {
        delete confirmPasswordControl.errors['mismatch'];
        if (Object.keys(confirmPasswordControl.errors).length === 0) {
          confirmPasswordControl.setErrors(null);
        }
      }
    }
    return null;
  }

  // 提交表单
  onSubmit(): void {
    if (this.registerForm.valid) {
      this.loading = true;
      const formValue = this.registerForm.value;

      const signupData: SignupRequest = {
        name: formValue.name!,
        email: formValue.email!,
        password: formValue.password!
      };

      this.authService.signup(signupData).subscribe({
        next: (response) => {
          this.loading = false;
          this.message.success('注册成功！请前往登录页面登录。');
          // 注册成功后跳转到登录页面
          this.router.navigate(['/login']);
        },
        error: (error) => {
          this.loading = false;
          console.error('注册失败:', error);

          let errorMessage = '注册失败，请稍后重试';
          if (error.error && error.error.message) {
            errorMessage = error.error.message;
          } else if (error.message) {
            errorMessage = error.message;
          }

          this.message.error(errorMessage);
        }
      });
    } else {
      // 标记所有字段为已触碰，以显示验证错误
      Object.values(this.registerForm.controls).forEach(control => {
        control.markAsTouched();
      });
    }
  }

  // 跳转到登录页面
  goToLogin(): void {
    this.router.navigate(['/login']);
  }

  // 获取表单控件的验证状态
  getFieldError(fieldName: string): string {
    const field = this.registerForm.get(fieldName);
    if (field && field.errors && field.touched) {
      if (field.errors['required']) {
        const fieldNames: { [key: string]: string } = {
          'name': '姓名',
          'email': '邮箱',
          'password': '密码',
          'confirmPassword': '确认密码'
        };
        return `${fieldNames[fieldName]}不能为空`;
      }
      if (field.errors['email']) {
        return '请输入有效的邮箱地址';
      }
      if (field.errors['minlength']) {
        const requiredLength = field.errors['minlength'].requiredLength;
        if (fieldName === 'name') {
          return `姓名至少需要${requiredLength}个字符`;
        } else if (fieldName === 'password') {
          return `密码至少需要${requiredLength}个字符`;
        }
      }
      if (field.errors['mismatch']) {
        return '两次输入的密码不一致';
      }
      if (field.errors['requiredTrue']) {
        return '请同意用户协议';
      }
    }
    return '';
  }

  // 检查字段是否有错误
  hasFieldError(fieldName: string): boolean {
    const field = this.registerForm.get(fieldName);
    return !!(field && field.errors && field.touched);
  }
}
